import React, { useEffect, useState } from 'react'
import { Card,Button ,Space, Table, Input ,Pagination, Modal, Upload, message, Form } from 'antd';
// import type { ColumnsType } from 'antd/es/table';

import "./index.less"
import { reqAddTrademark, reqAllTrademark, reqDelTrademark, reqEditTrademark, reqTrademarkInfo, reqTrademarkList } from '@/api/brand/idnex';
import { IAddEditParams, IReqListRecord, IReqTrademarkList } from '@/types/Trademark';
import { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/lib/upload';
import { DeleteOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useForm } from 'antd/lib/form/Form';
// import { setegid } from 'process';

export default function Brand() {


  const columns:any = [
    {
      title: '序号',
      dataIndex: 'id',      
  
    },
    {
      title: '品牌名称',
      dataIndex: 'tmName',     
     
    },
    {
      title: '品牌Logo',
      dataIndex: 'logoUrl',
      render:(a:any) =>{  
        return <img className='img' src={a} alt=''/>
      }

    },
    {
      title: '操作',  
      dataIndex: 'id',
     
      render(id:number,a:any,b:any) {
        // console.log(id)
       return(
       
       <>
        <Button onClick={()=>clickhandoff(id)}>修改</Button>&emsp;
        <Button icon={<DeleteOutlined rev={undefined}/>} onClick={() => removeTrademark(id)}>删除</Button>
        </>)
       
        
      }
    
    },
  ]


 

  // 列表详情数据
  const [records,setrecords] = useState<IReqListRecord[]>([])
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  // const [loading, setLoading] = useState(false)
  const [loading, setLoading] = useState(false);

  const [logo,setlogo] = useState<any>()

  const [id,setid] = useState<any>()
  
//  const [logoUrl2,setlogoUrl2] = useState<any>()

  const [isModalOpen, setIsModalOpen] = useState(false);

  const [isEdit,setisEdit] = useState<string>('新增品牌')

  // 编辑品牌
  const clickhandoff =(id:number) =>{
    setIsModalOpen(true);
    setisEdit("编辑品牌")


    getTrademarkInfo(id)
    // form.setFieldValue() 

    // putEditTrademark(data)
    

  }
 
  const showModal = () => {
    setisEdit("新增品牌")
    setIsModalOpen(true);
  };

  const handleOk = (id:number) => {
    setIsModalOpen(false);

    // form.validateFields()
    // .then((values) => {
    //   // console.log(values);
    
    // const data = {
    //   tmName: values.tmName,
    //   logoUrl: values.logoUrl.file.response.data
    // }
    // setdata(data)
    // getAddTrademark(data)

    // // return data
    // })
    // console.log()
    const tmName = form.getFieldValue("tmName")
    const logoUrl = form.getFieldValue("logoUrl")

    // const logoUrldata  = logoUrl
    // console.log(tmName)


    // console.log(isEdit)
    console.log(logoUrl)
    const data = {
      id:id,
      tmName:tmName,
      logoUrl:logoUrl ? logoUrl.file.response.data : logo
    }
    
    console.log("==>",data)
    // 调用添加方法
    if(data.id){
      getAddTrademark(data)

    }
    if(isEdit === "编辑品牌"){
      // console.log(data)
      // console.log("执行了")
      // if(data.logoUrl === logoUrl){
      //   data.logoUrl=== 
      // }
      putEditTrademark(data)
        // console.log(111)
      // setlogo('')

    }

    
  };

  const handleCancel = () => {
    setlogo('')
    setIsModalOpen(false);

    form.resetFields()
  };

  useEffect(()=>{
    getTrademarkList()
    // console.log(11)
    getAllTrademark()

  },[])


  // console.log(22)
  // 获取品牌列表数据
  const getTrademarkList =async (page = current, limit = pageSize) =>{
    setLoading(true)

    const res = await reqTrademarkList(page, limit )
    // console.log(res.data)
    setrecords(res.data.records)
    setCurrent(res.data.current)
    setPageSize(res.data.size)
    setTotal(res.data.total)
    setLoading(false)

    // setey(res.data)
  }
  // 获取全部列表数据
  const getAllTrademark = async() =>{
    const res = await reqAllTrademark()
    // setey(res.data.)
    // console.log(res.data)
  }


// 删除指定id的品牌

const removeTrademark = async (id: number) => {

  // 发送请求，只会删除服务器数据，客户端数据没变
  await reqDelTrademark(id);
  message.success("删除成功");
  // 重新获取最新商品列表即可
  getTrademarkList(current, pageSize);
} 

// 新增商品
const getAddTrademark = async (data:IAddEditParams) =>{
  console.log(data)
  await reqAddTrademark(data)
  message.success("添加成功");

  // console.log(res)

}

// 获取单个品牌属性
const getTrademarkInfo = async (id :number) =>{
setid(id)
const res =  await reqTrademarkInfo(id)
setlogo(res.data.logoUrl)
// setlogoUrl2(res.data.logoUrl)
//  console.log(res)
 const tmName = res.data.tmName
//  const logoUrl = res.data.logoUrl

//  console.log(tmName)
 form.setFieldValue("tmName",tmName)
//  form.setFieldValue("logoUrl",logo)

  // message.success("修改成功")
}
const putEditTrademark =async (data:any) =>{
  // console.log(1111)
  // console.log(data)
  await reqEditTrademark(data)
  // console.log(res)
  message.success("修改成功")
  getTrademarkList()

}

// console.log(logo)

  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setlogo(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined rev={undefined} /> : <PlusOutlined rev={undefined} />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const onFinish = (values: any) => {
    console.log(values);
  };

  const [form] = useForm()

  return (
    <div>
      
    <Card bordered={false} style={{ width: 1200  }} className='hearder' >

    
    
    <Button type="primary" onClick={showModal} style={{ marginBottom:20 }}>
       添加
      </Button>
      <Modal title={isEdit} open={isModalOpen} onOk={() =>handleOk(id)} onCancel={handleCancel}>
        <Form
        onFinish={onFinish}
        form={form}
        >

      <Form.Item name="tmName" label="品牌名称" rules={[{ required: true,message:"请输入品牌名称" }]}>
      <Input placeholder="请输入品牌名" />
      </Form.Item>
        
        <div   style={{marginTop:20}}>
      <Form.Item name="logoUrl" label="品牌logo" rules={[{ required: true,message:"请添加品牌logo" }]}>

      <Upload
      action="http://sph-h5-api.atguigu.cn/admin/product/upload"
      listType="picture-card"
      showUploadList={false}
      onChange={handleChange}
      beforeUpload={beforeUpload}
      >

      {logo ? <img src={logo} alt="avatar" style={{ width: 100}} /> : uploadButton}

            
          </Upload>

      </Form.Item>
        </div>
        </Form>

      </Modal>

    
   
    <Table
    rowKey='id' 
    columns={columns} 
    dataSource={records} 
    bordered={true} 
    pagination={{
      current,
      pageSize,
      total,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: (total) => `总共 ${total} 条`,
      onChange: getTrademarkList,
      onShowSizeChange: getTrademarkList,
    }}
    loading={loading}

    />

    {/* <Pagination defaultCurrent={6} total={500} />; */}

    </Card>
  
  
  
  </div>
  )
}


